<?php

namespace App\Services\User;

use App\Enums\CurStatusEnums;
use App\Enums\ResponseCode;
use App\Exceptions\BusinessException;
use App\Helpers\ValidatorTool;
use App\Models\User;
use App\Services\AbstractBaseService;
use App\Services\Easemob\EasemobService;
use App\Services\Im\WechatService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class UserService extends AbstractBaseService
{

    /**
     * 创建用户
     * @param string $mobile 手机号码或者邮箱
     * @return void
     * @throws BusinessException
     */
    public static function createUser(string $mobile): void
    {
        //判断用户输入的是否是邮箱或者手机号码
        if (!ValidatorTool::is_mobilePhone($mobile)) {
            self::exception(ResponseCode::VALIDATION_ERROR, trans("请输入手机号码"));
        }
        $lockKey = 'user-register-account:' . $mobile;
        $lock = Cache::lock($lockKey, 5);
        if ($lock->get()) {
            DB::beginTransaction();
            try {
                $data = [
                    'mobile' => $mobile,
                    'gender' => 0,
                    'avatar_url' => "",
                    'is_lock' => CurStatusEnums::STATUS_INVALID,
                ];
                $user = User::query()->create($data);
                // $username = 'user_uuid_'.$user->id;
                //注册环信 获取用户uuid
                // $EasemobService = new EasemobService;
                // $res = $EasemobService->createUser($username,"123456",$username);
                // User::query()->where("id",$user->id)->update(["uuid"=>$res["uuid"],"uuname"=>$username]);

                $ImWechat = new WechatService;
                $ImWechat->create('user_' . $user->id, 'user_' . $user->id, $user->defaultAvatar());
                //$username = 'shop_uuid_'.$user->id;
                User::query()->where("id", $user->id)->update(["is_im" => 1]);

                DB::commit();
                // 推送耗时任务到队列
            } catch (QueryException $exception) {
                DB::rollBack();
                self::exception(ResponseCode::SERVICE_UNAVAILABLE, config('app.debug') ? $exception->getMessage() : trans('注册数据异常退出'));
            } finally {
                $lock->release();
            }
        } else {
            self::exception(ResponseCode::LOCKED, trans('帐号正在注册中请勿重复提交'));
        }
    }

    /**
     * 微信授权手机号创建用户
     * @param string $mobile 手机号码或者邮箱
     * @return void
     * @throws BusinessException
     */
    public static function pcreateUser(string $mobile): void
    {
        //判断传入手机号
        if (empty($mobile)) {
            self::exception(ResponseCode::VALIDATION_ERROR, trans("手机号不能为空"));
        }
        DB::beginTransaction();
        try {
            $data = [
                'mobile' => $mobile,
                'type' => 2,
                'gender' => 0,
                'avatar_url' => "http://oss.charityzimi.cn/head_pic/epn87GOArZ2B9mYC5YWLJ44OmTrfjPkGN8vAZCmg.png",
                'is_lock' => CurStatusEnums::STATUS_INVALID,
            ];
            $user = User::query()->create($data);
            $username = 'user_uuid_' . $user->id;
            //注册环信 获取用户uuid
            // $EasemobService = new EasemobService;
            // $res = $EasemobService->createUser($username, "123456", $username);
            // if($user->gender == 2){
            //     $avatar_url = "https://oss.charityzimi.cn/head_pic/uK5hvgxZBrGs9oa9HkKOKtUG096nFm3ZQYey5Ht2.png";
            // }else{
            //     $avatar_url = "https://oss.charityzimi.cn/head_pic/JXYmXzdqJze4CleCazRrdKNwo0P2M4CgNJFuNDsf.png";
            // }
            $avatar_url = "http://oss.charityzimi.cn/head_pic/epn87GOArZ2B9mYC5YWLJ44OmTrfjPkGN8vAZCmg.png";
            // if (empty($user->name)) {
            //     $user_name = $user->id;
            // } else {
            //     $user_name = $user->name;
            // }

            $ImWechat = new WechatService;
            $ImWechat->create('user_' . $user->id, 'user_' . $user->id, $user->defaultAvatar());

            //设置环信用户属性  头像  昵称
            // $EasemobService->attribute($username, $avatar_url);
            // $EasemobService->attribute($username, $user_name);
            // User::query()->where("id", $user->id)->update(["uuid" => $res["uuid"], "uuname" => $username]);
            User::query()->where("id", $user->id)->update(["is_im" => 1]);
            DB::commit();
            // 推送耗时任务到队列
        } catch (QueryException $exception) {
            DB::rollBack();
            self::exception(ResponseCode::SERVICE_UNAVAILABLE, config('app.debug') ? $exception->getMessage() : trans('注册数据异常退出'));
        }
    }

    /**
     * 修改会员资料
     * @param int $UserId
     * @param array $info
     */
    public static function editPayProfile(int $UserId, array $info)
    {
        $infoKey = ['name', 'gender', 'birthday', 'identity', 'mobile', 'avatar_url', 'self_description'];
        $upDate = [];
        foreach ($infoKey as $item) {
            if (!empty($info[$item])) {
                $upDate[$item] = $info[$item];
            }
        }
        if (!empty($info['gender']) && in_array($info['gender'], [0, 1, 2])) {
            $upDate['gender'] = $info['gender'];
        }
        !empty($upDate) && User::where('id', '=', $UserId)->update($upDate);
        // $EasemobService = new EasemobService;
        $wechatIm = new WechatService;
        $user = User::query()->where("id", $UserId)->first();
        // if (!empty($upDate["name"])) {
        //     $EasemobService->attribute($user->uuname, ["nickname" => $upDate["name"]]);
        // }
        // if (!empty($upDate["avatar_url"])) {
        //     $EasemobService->attribute($user->uuname, ["avatarurl" => $upDate["avatar_url"]]);
        // }
        $wechatIm->attribute('user_' . $user->id, 'user_' . $user->id, $user->defaultAvatar());
    }
}
